package a51qindian.com.comprehensive.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * Author: Li
 * Date: 2017/9/19 0019
 * Description: 本地缓存
 */

public final class SpUtil {
    private SpUtil() {
    }

    private static final String SP_USER = "sp_user";
    private static final String USER_INFO = "user_info";
    public static final String USER_ID="user_id";
    public static final String USER_GRADE="user_grade";
    public static final String USER_MONEY="user_money";
    public static final String USER_NAME="user_name";
    public static final String USER_TOTAL_MONEY="user_total_money";
    public static final String USER_IS_SHOP="user_is_shop";
    public static final String USER_DEFAULT_ID="-1";

    public static SharedPreferences getUserSp(Context context) {
        return context.getSharedPreferences(SP_USER, Context.MODE_PRIVATE);
    }

    /**
     * 保存用户信息
     * @param context   上下文
     * @param userId    用户编号
     * @param money 余额
     * @param grade 等级
     * @param userName  账号名称
     */
    public static void saveUserInfo(Context context,
                                    String userId, String money,String grade,
                                    String userName,String totalMoney,String isShop) {
        SharedPreferences.Editor editor = getUserSp(context).edit();
        editor.putString(USER_ID, userId);
        editor.putString(USER_MONEY, money);
        editor.putString(USER_GRADE, grade);
        editor.putString(USER_NAME, userName);
        editor.putString(USER_TOTAL_MONEY,totalMoney);
        editor.putString(USER_IS_SHOP,isShop);
        editor.apply();
    }

    public static void updateUserInfo(Context context,String key,String value){
        SharedPreferences.Editor editor = getUserSp(context).edit();
        editor.putString(key,value);
        editor.apply();
    }
    public static String getUserInfo(Context context,String key){
        SharedPreferences preferences=getUserSp(context);
        return preferences.getString(key,"");
    }

    /**
     * 判断当前是否有用户存在
     * @param context   上下文
     * @return  true：存在   false：不存在
     */
    public static boolean isUserExist(Context context) {
        return !TextUtils.isEmpty(getUserInfo(context, USER_ID));
    }


    /**
     * 清除用户缓存信息
     *
     * @param context 上下文
     */
    public static void clearUserInfo(Context context) {
        SharedPreferences.Editor editor = getUserSp(context).edit();
        editor.clear();
        editor.apply();
    }


}
